let port;

export function reconnectToNativeApp() {
    if (!port || port.disconnect) {
        port = chrome.runtime.connectNative('yonyou.rpa.chromeapp');
        port.onDisconnect.addListener(() => {
            console.log('Native connection lost, attempting to reconnect...');
            port = null;
        });
        port.onMessage.addListener((message) => {
            console.log('Received message from native app:', message);
        });
        console.log('Reconnected to native app.');
    } else {
        try {
            port.postMessage({
                data: 'ping',
            });
        } catch (error) {
            // port.disconnect();
            port = null;
        }
    }
}

export function postNativeMessage(message) {
    try {
        port.postMessage(message);
    } catch (error) {
        console.error(error);
    }
}

async function createAlarm() {
    const ALARM_NAME = 'keep-message-alive';
    const alarm = await chrome.alarms.get(ALARM_NAME);
    if (typeof alarm === 'undefined') {
        chrome.alarms.create(ALARM_NAME, {
            delayInMinutes: 5 / 60, // 延迟 5 秒 (5 秒 = 5/60 分钟)
            periodInMinutes: 1 / 6, // 每 10 秒触发一次 (10 秒 = 1/6 分钟)
        });
        reconnectToNativeApp();
    }
}

createAlarm();

chrome.alarms.onAlarm.addListener(reconnectToNativeApp);
